﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace SW.Core
{
    /// <summary>
    /// CSV文件辅助类
    /// </summary>
    public class CSVHelper
    {
        /// <summary>
        /// 将DataTable转化为CSV
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name="filePath">存储文件</param>
        /// <param name="columnNames">列名集合</param>
        public static bool DataTable2CSV(DataTable dtSource, string filePath, string[] columnNames)
        {
            try
            {
                string strBufferLine = "";
                StreamWriter strmWriterObj = new StreamWriter(filePath, false, System.Text.Encoding.UTF8);
                strmWriterObj.WriteLine(String.Join(",", columnNames));
                for (int i = 0; i < dtSource.Rows.Count; i++)
                {
                    strBufferLine = "";
                    for (int j = 0; j < dtSource.Columns.Count; j++)
                    {
                        if (j > 0)
                            strBufferLine += ",";
                        strBufferLine += dtSource.Rows[i][j].ToString();
                    }
                    strmWriterObj.WriteLine(strBufferLine);
                }
                strmWriterObj.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 将CSV读入DataTable
        /// </summary>
        /// <param name="filePath">CSV文件路径</param>
        /// <param name="dtSource">数据源</param>
        public static DataTable CSV2DataTable(string filePath, DataTable dtSource)
        {
            StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
            int i = 0, m = 0;
            reader.Peek();
            while (reader.Peek() > 0)
            {
                m = m + 1;
                string str = reader.ReadLine();
                if (m >= 1)
                {
                    string[] split = str.Split(',');

                    System.Data.DataRow dr = dtSource.NewRow();
                    for (i = 0; i < split.Length; i++)
                    {
                        dr[i] = split[i];
                    }
                    dtSource.Rows.Add(dr);
                }
            }
            return dtSource;
        }
    }
}
